package services

import (
	"errors"
	"fmt"
	"gameTest/common"
	"gameTest/datamodels"
	"gameTest/repositories"
	"github.com/opentracing/opentracing-go/log"
	"golang.org/x/crypto/bcrypt"
	"time"
)

type IUserService interface {
	IsPwdSuccess(userName string, pwd string) (user *datamodels.User, isOk bool)
	AddUser(user *datamodels.User) (userId int64, err error)
}

func NewUserService(repository repositories.IUserRepository) IUserService {
	return &UserService{repository}
}

type UserService struct {
	UserRepository repositories.IUserRepository
}

func (u *UserService) IsPwdSuccess(userName string, pwd string) (user *datamodels.User, isOk bool) {
	user, err := u.UserRepository.Select(userName)
	if err != nil {
		return
	}
	isOk, _ = ValidatePassword(pwd, user.HashPassword)
	if !isOk {
		return
	}
	user.AuthToken = common.GetRandomString(20)
	//user.ExpireAt = time.Now().Format("2006-01-02 15:04:05")
	during, _ := time.ParseDuration("10m")//一分钟之后 -1一分钟之前 1h1小时 1m十分钟

	user.ExpireAt = time.Now().Add(during).Format("2006-01-02 15:04:05")
	errUpdate := u.UserRepository.UpdateToken(user)
	fmt.Println(user.ID)
	if errUpdate != nil {
		log.Error(errUpdate)
	}
	return
}

func (u *UserService) AddUser(user *datamodels.User) (userId int64, err error) {
	pwdByte, errPwd := GeneratePassword(user.HashPassword)
	if errPwd != nil {
		return userId, errPwd
	}
	user.HashPassword = string(pwdByte)
	return  u.UserRepository.Insert(user)
}

func GeneratePassword(userPassword string) ([]byte, error)  {
	return bcrypt.GenerateFromPassword([]byte(userPassword), bcrypt.DefaultCost)
}

func ValidatePassword(userPassword string, hashed string) (isOk bool, err error) {
	if err = bcrypt.CompareHashAndPassword([]byte(hashed), []byte(userPassword)); err != nil {
		return false, errors.New("密码错误!")
	}
	return  true, nil
}



